package com.songshuai.webapi.jobapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.songshuai.webapi.jobapi.common.settings.CacheKeys;
import com.songshuai.webapi.jobapi.dto.base.BaseVigoRes;
import com.songshuai.webapi.jobapi.dto.response.Tpo_Sys_User;
import com.songshuai.webapi.jobapi.dto.response.VigoUsers;
import com.songshuai.webapi.jobapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户业务实现层
 * <p>
 * Created by bysocket on 07/02/2017.
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Value("${config.self.vigohost}")
    private String vigoHost;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Tpo_Sys_User getUserById(Integer userId) {
        Tpo_Sys_User userInfo = null;
        if (userId==null||userId <= 0) {
            return userInfo;
        }
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        List<Tpo_Sys_User> users = getUsers(userIds);
        if (users != null && users.size() > 0) {
            userInfo = users.get(0);
        }
        return userInfo;
    }

    @Override
    public List<Tpo_Sys_User> getUsers(List<Integer> userIds) {
        List<Tpo_Sys_User> retList = new ArrayList<>();
        if (userIds == null || userIds.size() == 0)
            return retList;
        userIds = userIds.stream().filter(f -> f != null && f > 0).distinct().collect(Collectors.toList());
        List<String> idsKeys = new ArrayList<>();
        for (Integer id : userIds) {
            String key = CacheKeys.VIGO_USER_INFO_KEY + id;
            idsKeys.add(key);
        }
        ValueOperations<String, Tpo_Sys_User> operations = redisTemplate.opsForValue();
        List<Tpo_Sys_User> tempDictionarys = new ArrayList<>();
        try {
            tempDictionarys=operations.multiGet(idsKeys);
            if(tempDictionarys==null){
                tempDictionarys=new ArrayList<>();
            }
        } catch (Exception ex) {
            log.error("get cache error");
        }

        List<Integer> tempIds = new ArrayList<>();
        tempDictionarys.remove(null);
        if (tempDictionarys != null && tempDictionarys.size() > 0) {
            tempIds = tempDictionarys.stream().filter(c -> c != null && c.getUserID() > 0).map(Tpo_Sys_User::getUserID).collect(Collectors.toList());
            retList = tempDictionarys;
            if (tempDictionarys.size() == userIds.size()) {
                return retList;
            }
        }
        userIds.removeAll(tempIds);
        String reqUrl = vigoHost + "/api/v1/getusers";
        StringBuilder sBuilder = new StringBuilder();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        for (Integer uid : userIds) {
            sBuilder.append(String.format("&userIds[]=%s", uid));
        }
        if (sBuilder.length() > 0) {
            sBuilder.delete(0, 1);
        }
        try {
            HttpEntity entity = new HttpEntity(sBuilder.toString(), headers);
            ResponseEntity<String> res = restTemplate.exchange(reqUrl, HttpMethod.POST, entity, String.class);
            BaseVigoRes<VigoUsers> usersInfo = JSON.parseObject(res.getBody(), new TypeReference<BaseVigoRes<VigoUsers>>() {
            });
            if(usersInfo==null||usersInfo.getResult()==null||usersInfo.getResult().getTpo_Sys_Users()==null){
                return retList;
            }
            try {//数据放入缓存
                for (Tpo_Sys_User u : usersInfo.getResult().getTpo_Sys_Users()) {
                    retList.add(u);
                    operations.set(CacheKeys.VIGO_USER_INFO_KEY + u.getUserID(), u, 5, TimeUnit.MINUTES);
                }
            } catch (Exception ex) {
                log.error("permission cache set error", ex);
            }

        } catch (Exception ex) {
            log.error("get permission user error", ex);
        }
        return retList;
    }

    @Override
    public String getUserNameById(Integer userId) {
        String retData = "";
        if (userId==null|| userId <= 0) {
            return retData;
        }
        Tpo_Sys_User userInfo = getUserById(userId);
        if (userInfo != null) {
            retData = userInfo.getTrueName();
        }
        return retData;
    }

    @Override
    public Map<Integer, Tpo_Sys_User> getUserMaps(List<Integer> userIds) {
        Map<Integer, Tpo_Sys_User> retMap = new HashMap<>();
        List<Tpo_Sys_User> users = getUsers(userIds);
        if (users == null || users.size() == 0) {
            return retMap;
        }
        for (Tpo_Sys_User u : users) {
            retMap.put(u.getUserID(), u);
        }
        return retMap;
    }

    @Override
    public Map<Integer, String> getUserNameMaps(List<Integer> userIds) {
        Map<Integer, String> retMap = new HashMap<>();
        if(userIds==null||userIds.size()==0){
            return retMap;
        }
        List<Tpo_Sys_User> users = getUsers(userIds);
        if (users == null || users.size() == 0) {
            return retMap;
        }
        for (Tpo_Sys_User u : users) {
            retMap.put(u.getUserID(), u.getTrueName());
        }
        return retMap;
    }
}
